<script setup lang="ts">
import WaveSurfer from 'wavesurfer.js'

defineOptions({
    name: 'AudioVisualization'
})

const $props = defineProps(['src'])

const audioRef = shallowRef()

const wavesurfer = shallowRef<WaveSurfer | null>(null)

const $emit = defineEmits<{ onReady: [duration: number], onClick: [], onFinish: [] }>()

nextTick(() => {
    wavesurfer.value = WaveSurfer.create({
        container: audioRef.value,
        waveColor: '#BBBBBB',
        progressColor: 'transparent',
        url: $props.src,
        barHeight: 1.4,
        barWidth: 2,
        height: 50,
        barGap: 5,
    })
    wavesurfer.value.on('click', () => {
        wavesurfer.value?.setOptions({
            progressColor: '#E62129'
        })
        $emit('onClick')
    })

    wavesurfer.value?.on('ready', (duration: number) => {
        $emit('onReady', Math.ceil(duration))
    })

    wavesurfer.value?.on('finish', () => {
        $emit('onFinish')
    })
})

function play() {
    wavesurfer.value?.setOptions({
        progressColor: '#E62129'
    })
    wavesurfer.value?.play()
}

function pause() {
    wavesurfer.value?.pause()
}

function getCurrentTime() {
    return wavesurfer.value?.getCurrentTime()
}


defineExpose({ play, pause, getCurrentTime })

</script>

<template>
    <div class="audio-visualization" ref="audioRef"></div>
</template>

<style lang="scss" scoped>
.audio-visualization {
    width: 100%;
}
</style>
